package com.itheima.project.handler.impl;

import com.itheima.project.constant.security.OauthConstant;
import com.itheima.project.core.enums.security.AuthEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.feign.CustomerAdapterFeign;
import com.itheima.project.feign.DataDictFeign;
import com.itheima.project.feign.UserAdapterFeign;
import com.itheima.project.handler.CacheTokenHandler;
import com.itheima.project.handler.LoginAuthHandler;
import com.itheima.project.utils.BeanConv;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.vo.dict.DataDictVo;
import com.itheima.project.vo.security.CustomerVo;
import com.itheima.project.vo.security.EnterpriseVo;
import com.itheima.project.vo.security.UserVo;
import com.itheima.project.wechat.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;

import java.security.Principal;
import java.util.Map;

/**
 * @ClassName WechatLoginAuthHandlerImpl.java
 * @Description 微信登录处理
 */
@Component("wechatLoginAuthHandler")
public class WechatLoginAuthHandlerImpl implements LoginAuthHandler {

    //调用RPC原创服务
    @Autowired
    UserAdapterFeign userAdapterFeign;

    //调用RPC原创服务
    @Autowired
    CustomerAdapterFeign customerAdapterFeign;

    @Autowired
    DataDictFeign dataDictFeign;

    @Autowired
    TokenEndpoint tokenEndpoint;

    @Autowired
    CacheTokenHandler cacheTokenHandler;

    @Autowired
    WechatService wechatService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserVo loginHandler(Principal principal, Map<String, String> parameters, EnterpriseVo enterpriseVo)
            throws HttpRequestMethodNotSupportedException {
        String enterpriseId = String.valueOf(enterpriseVo.getEnterpriseId());
        String code = parameters.get(OauthConstant.CODE_KEY);
        String clientId = parameters.get(OauthConstant.CLIENT_ID_KEY);
        String loginType = parameters.get(OauthConstant.LOGIN_TYPE_KEY);
        //code兑换openId
        String openId = wechatService.openId(enterpriseVo.getAppId(), enterpriseVo.getAppSecret(), code);
        String username = openId+"#"+enterpriseId+"#"+clientId+"#"+loginType;
        parameters.put(OauthConstant.USER_NAME_KEY,username);
        parameters.put(OauthConstant.PASSWORD_KEY,openId);
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        return cacheTokenHandler.cacheToken(oAuth2AccessToken);
    }

    @Override
    public UserVo findUserDetail(String loginType, String openId, Long enterpriseId) {
        //处理登录
        UserVo userVo = null;
        String password = bCryptPasswordEncoder.encode(openId);
        switch (loginType){
            case OauthConstant.USER_WECHAT:
                userVo = userAdapterFeign.findUserByOpenIdAndEnterpriseId(openId, enterpriseId).getDatas();
                //如果用户不存在则注册用户
                if (EmptyUtil.isNullOrEmpty(userVo)){
                    userVo = new UserVo();
                    userVo.setUsername(openId);
                    userVo.setOpenId(openId);
                    userVo.setPassword(openId);
                    userVo.setEnterpriseId(enterpriseId);
                    //默认用户角色
                    DataDictVo dataDictVo = dataDictFeign.findDataDictVoByDataKey(OauthConstant.DEFAULT_ROLE_USER).getDatas();
                    String[] roleIds = new String[]{dataDictVo.getDataValue()};
                    userVo.setHasRoleIds(roleIds);
                    userVo = userAdapterFeign.registerUser(userVo).getDatas();
                }
                userVo.setPassword(password);
                return userVo;
            case OauthConstant.CUSTOMER_WECHAT:
                userVo = customerAdapterFeign.findCustomerByOpenIdAndEnterpriseId(openId, enterpriseId).getDatas();
                //如果用户不存在则注册用户
                if (EmptyUtil.isNullOrEmpty(userVo)){
                    CustomerVo customerVo = new CustomerVo();
                    customerVo.setUsername(openId);
                    customerVo.setOpenId(openId);
                    userVo.setPassword(openId);
                    userVo.setEnterpriseId(enterpriseId);
                    //默认客户角色
                    DataDictVo dataDictVo = dataDictFeign.findDataDictVoByDataKey(OauthConstant.DEFAULT_ROLE_CUSTOMER).getDatas();
                    String[] roleIds = new String[]{dataDictVo.getDataValue()};
                    customerVo.setHasRoleIds(roleIds);
                    customerVo  = customerAdapterFeign.registerUser(customerVo).getDatas();
                    return BeanConv.toBean(customerVo,UserVo.class);
                }
                userVo.setPassword(password);
                return userVo;
            default:
                throw new ProjectException(AuthEnum.LOGIN_FAIL);
        }
    }
}
